package simple; /**
 * @projectName study-note
 * @package PACKAGE_NAME
 * @className PACKAGE_NAME.CharIsValid
 */

import java.util.*;

/**
 * CharIsValid
 * @description 只包含括号的字符串是否有效
 * @author answer_wx
 * @date 2022/6/30 10:10
 * @version 1.0
 */
public class CharIsValid {
    public static boolean isValid(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }
        HashMap<Character, Character> brackets = new HashMap<>();
        brackets.put('(', ')');
        brackets.put('{', '}');
        brackets.put('[', ']');
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < chars.length; i++) {
            if (brackets.containsKey(chars[i])) {
                stack.add(brackets.get(chars[i]));
            } else {
                if (brackets.containsValue(chars[i])) {
                    if (stack.isEmpty() || !stack.pop().equals(chars[i])) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        return stack.empty();
    }

    public static void main(String[] args) {
        String s = "{()}*";
        System.out.println(isValid(s));
    }
}